package com.member.mp.web;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.core.domain.R;
import com.member.common.core.page.PageResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.EnableStatusEnum;
import com.member.common.enums.OrderDeleteEnum;
import com.member.common.utils.StringUtils;
import com.member.mp.web.user.SupperController;
import com.member.shop.domain.*;
import com.member.shop.dto.SysBizCouponMap;
import com.member.shop.service.*;
import com.member.shop.vo.GoodsEntity;
import com.member.shop.vo.GoodsIndexVo;
import com.member.shop.vo.UserCouponVo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static com.member.common.enums.DeleteEnum.NOT_DELETE;

/**
 * 【优惠券】控制器
 *
 * @author wangxin
 * @version 1.0
 * @date 2024-05-11 18:20
 **/
@Api(value = "优惠券接口", tags = {"优惠券接口"})
@RestController
@RequestMapping("/wx/coupon")
@Slf4j
public class CouponController extends SupperController {


    @Resource
    private ISysBizCouponReceiveService sysBizCouponReceiveService;
    @Resource
    private ISysBizCouponGoodsUserService sysBizCouponGoodsUserService;
    @Resource
    private ISysBizUserService sysBizUserService;
    @Resource
    private ISysBizUserCollectService sysBizUserCollectService;
    @Resource
    private ISysBizGoodsService sysBizGoodsService;
    @Resource
    private ISysBizCouponService sysBizCouponService;
    @Resource
    private ISysBizCouponGrantService sysBizCouponGrantService;
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    public static final String CART_KEY = "CART:";

    private String getCartKey() {
        SysBizUser loginUser = getLoginUser();
        Long userId = loginUser.getId();
        Long tenantId = loginUser.getTenantId();
        String key = CART_KEY + tenantId + ":" + userId;
        return key;
    }

    /**
     * 领取优惠券
     *
     * @param id 优惠券id
     * @return 领取优惠券
     */
    @PostMapping("/receiveCoupon")
    public R<String> receiveCoupon(@RequestParam("id") Long id) {
        try {

            SysBizUser loginUser = getLoginUser();
            Long userId = loginUser.getId();
            SysBizCoupon byId = sysBizCouponService.getById(id);

            if (byId == null) {
                return R.fail("优惠券不存在");
            }

            if (byId.getDeleted().equals(1) || byId.getDisplayed().equals(1)) {
                return R.fail("优惠券已删除");
            }
            if (byId.getValidityType().equals(1) && byId.getTermEndTime().compareTo(new Date()) < 0) {
                return R.fail("优惠券已过期");
            }
            // 领取逻辑
            int receiveStatus = getReceiveStatus(userId, byId);

            if (receiveStatus == 1) {
                return R.fail("优惠券已领取");
            }

            sysBizCouponGrantService.createCouponReceiveRecord(loginUser, byId, 0);


            return R.ok();
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("领取优惠券列表失败", e);
            return R.fail("领取优惠券列表失败，请稍后尝试");
        }
    }

    /**
     * 查询优惠券列表
     *
     * @return 查询优惠券列表
     */
//    @GetMapping("/queryCoupon")
    public R<PageResult<SysBizCoupon>> queryCoupon(@RequestParam("name") String name) {
        try {
            startPage();
            Long tenantId = getTenantId();
            LambdaQueryWrapper<SysBizCoupon> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizCoupon::getDeleted, NOT_DELETE.getKey());
            queryWrapper.eq(SysBizCoupon::getName, name);
            queryWrapper.eq(SysBizCoupon::getTenantId, tenantId);
            queryWrapper.eq(SysBizCoupon::getDisplayed, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.orderByDesc(SysBizCoupon::getOrderNum);
            queryWrapper.orderByDesc(SysBizCoupon::getCreateTime);
            List<SysBizCoupon> list = sysBizCouponService.list(queryWrapper);
            TableDataInfo dataTable = getDataTable(list);
            List<?> rows = dataTable.getRows();

            List<SysBizCoupon> collect = rows.stream().map(p -> (SysBizCoupon) p).collect(Collectors.toList());
            Long userId = getUserId();

            for (SysBizCoupon sysBizCoupon : collect) {

                int receiveStatus = getReceiveStatus(userId, sysBizCoupon);
                sysBizCoupon.setReceiveStatus(receiveStatus);
            }


            return R.ok(new PageResult<>(dataTable.getTotal(), collect));
        } catch (Exception e) {
            // 异常处理，日志记录，返回友好的错误信息
            log.error("查询优惠券列表失败", e);
            return R.fail("查询优惠券列表失败，请稍后尝试");
        }
    }

    private int getReceiveStatus(Long userId, SysBizCoupon sysBizCoupon) {
        LambdaQueryWrapper<SysBizCouponReceive> receiveLambdaQueryWrapper = new LambdaQueryWrapper<>(

        );
        receiveLambdaQueryWrapper.eq(SysBizCouponReceive::getUserId, userId);
        receiveLambdaQueryWrapper.eq(SysBizCouponReceive::getCouponId, sysBizCoupon.getId());
        List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.list(receiveLambdaQueryWrapper);
        if (!CollectionUtils.isEmpty(sysBizCouponReceives) && sysBizCouponReceives.size() >= sysBizCoupon.getUserLimit()) {
            return 1;
        }
        return 0;
    }

    /**
     * 查询用户领取优惠券（带分页）
     *
     * @param status 状态（0：未使用，1：已使用, 2：已过期，null:全部）
     * @return 优惠券列表
     */
    @GetMapping("/queryCouponByUser")
    public R<PageResult<UserCouponVo>> queryCouponByUser(@RequestParam(value = "status", required = false) Integer status) {
        SysBizCouponReceive build = SysBizCouponReceive.builder().tenantId(getTenantId()).userId(getUserId()).build();
        if (status != null) {
            build.setStatus(status);
        } else {
            //2025/03/25 优惠券只查未使用的
            build.setStatus(0);
        }
        startPage();
        List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.queryCouponByUser(build);
        TableDataInfo dataTable = getDataTable(sysBizCouponReceives);
        List<?> rows = dataTable.getRows();
        ArrayList<UserCouponVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizCouponReceive sysBizCouponReceive = (SysBizCouponReceive) row;
            UserCouponVo target = new UserCouponVo();
            BeanUtils.copyProperties(sysBizCouponReceive, target);
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * 查询商品优惠券
     * 苹果 和 安卓 1.6以下用的这个 后续会弃用，新版本请勿使用这个接口 by 2025-5-13
     * @param goodsIdList 商品id列表
     * @param sum      总金额
     * @return 优惠券列表
     */
    @GetMapping("/queryCouponByGoodsIds")
    public R<Map<String, List<UserCouponVo>>> queryCouponByGoodsIds(@RequestParam("goodsIds") List<Long> goodsIdList, @RequestParam("sum") BigDecimal sum) {
        SysBizUser loginUser = getLoginUser();
        Long userId = loginUser.getId();
        Long tenantId = loginUser.getTenantId();
        SysBizCouponReceive build = SysBizCouponReceive.builder().status(0).tenantId(tenantId).userId(userId).build();
        List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.queryCouponByUser(build);

        List<UserCouponVo> available = new ArrayList<>();
        List<UserCouponVo> notAvailable = new ArrayList<>();

        for (SysBizCouponReceive sysBizCouponReceive : sysBizCouponReceives) {
            UserCouponVo target = new UserCouponVo();
            BeanUtils.copyProperties(sysBizCouponReceive, target);

            BigDecimal thresholdAmount = target.getThresholdAmount();
            if (thresholdAmount.compareTo(sum) > 0) {
                target.setValidStatus(1);
            } else {
                if (target.getTermEndTime().compareTo(new Date()) > 0 && target.getTermBeginTime().compareTo(new Date()) < 0) {
                    target.setValidStatus(0);
                    // 指定商品
                    if (2 == sysBizCouponReceive.getScopeUse()) {
                        target.setValidStatus(1);
                        SysBizCouponGoodsUser sysBizCouponGoodsUser = sysBizCouponGoodsUserService.getByUserIdAndReceiveIdByGoodsIds(userId, sysBizCouponReceive.getId(), goodsIdList);

                        if (sysBizCouponGoodsUser != null) {
                            target.setValidStatus(0);
                        }
                    }
                    // 指定分类
                    if (3 == sysBizCouponReceive.getScopeUse()) {
                        List<SysBizGoods> list = sysBizGoodsService.list(new LambdaQueryWrapper<SysBizGoods>().in(SysBizGoods::getId, goodsIdList));
                        List<Long> uniqueCategoryIds = list.stream()
                                .map(SysBizGoods::getCategoryId)
                                .distinct()
                                .collect(Collectors.toList());

                        List<Long> uniqueCategoryTwoIds = list.stream()
                                .map(SysBizGoods::getCategoryTwoId)
                                .distinct()
                                .collect(Collectors.toList());

                        if (uniqueCategoryIds.size() > 1) {
                            target.setValidStatus(1);
                        } else {
                            if (!CollectionUtils.isEmpty(uniqueCategoryTwoIds) && StringUtils.isNotBlank(sysBizCouponReceive.getClassId())) {
                                log.info("-----------sysBizCouponReceive.getClassId():" + sysBizCouponReceive.getClassId());
                                // 字符串转Long集合
                                List<Long> classIds = Arrays.stream(sysBizCouponReceive.getClassId().split(","))
                                        .map(String::trim)
                                        .filter(s -> !s.isEmpty())
                                        .map(Long::parseLong)
                                        .collect(Collectors.toList());
                                log.info("-----------classIds:" + classIds.size());
                                log.info("-----------uniqueCategoryTwoIds:" + uniqueCategoryTwoIds.size());
                                // 优惠劵只指定了二级分类中的一个
                                if (classIds.size() == 1 && uniqueCategoryTwoIds.size() > 1) {
                                    target.setValidStatus(1);
                                } else {
                                    // 判断是否存在交集
                                    boolean hasIntersection = !Collections.disjoint(classIds, uniqueCategoryTwoIds);
                                    target.setValidStatus(hasIntersection ? 0 : 1);
                                }
                            } else {
                                target.setValidStatus(1);
                            }
                        }
                    }
                } else {
                    target.setValidStatus(2);
                }
            }

            if (target.getValidStatus() == 0) {
                available.add(target);
            } else {
                notAvailable.add(target);
            }
        }

        Map<String, List<UserCouponVo>> result = new HashMap<>();
        result.put("available", available);
        result.put("notAvailable", notAvailable);

        return R.ok(result);
    }

    /**
     * 查询商品优惠券 后续使用这个接口 业务逻辑由上面接口 更改调整而来！！！
     *
     * @param skuIds 商品skuId列表
     * @param sum    总金额      这个是前端传的代码逻辑不能直接用
     * @return 优惠券列表
     */
    @GetMapping("/queryCouponByGoodsIds2")
    public R<Map<String, List<UserCouponVo>>> queryCouponByGoodsIds2(@RequestParam("skuIds") List<Long> skuIds,
                                                                     @RequestParam("sum") BigDecimal sum) {
        SysBizUser loginUser = getLoginUser();
        Long userId = loginUser.getId();
        Long tenantId = loginUser.getTenantId();

        SysBizUser sysBizUser = sysBizUserService.selectSysBizUserById(getUserId());

        SysBizCouponReceive build = SysBizCouponReceive.builder().status(0).tenantId(tenantId).userId(userId).build();
        // 查询当前用户所有的优惠劵List
        List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.queryCouponByUser(build);

        List<SysBizGoods> list = new ArrayList<>();
        // 根据商品id查看商品List价格 sku表
        List<SysBizGoodsSku> skuList = sysBizGoodsSkuService.list(new LambdaQueryWrapper<SysBizGoodsSku>().in(SysBizGoodsSku::getId, skuIds));

        // 从购物车获取购买商品数量
        String key = getCartKey();
        BoundHashOperations<String, Object, Object> cartMap = stringRedisTemplate.boundHashOps(key);
        // 获取所有的购物车数据
        List<Object> cartList = cartMap.values();
        List<GoodsEntity> items = new ArrayList<>();
        if (org.apache.commons.collections.CollectionUtils.isNotEmpty(cartList)) {
            for (Object item : cartList) {
                String objStr = (String) item;
                GoodsEntity goodVo = JSON.parseObject(objStr, GoodsEntity.class);
                // 查询价格
                SysBizGoodsSku sysBizGoodsSku = sysBizGoodsSkuService.selectSysBizGoodsSkuByGoodsIdAndKey(goodVo.getGoodsId(), goodVo.getSpecsKey());
                if (goodVo == null) {
                    continue;
                }
                if (sysBizGoodsSku == null) {
                    continue;
                }
                goodVo.setSkuId(sysBizGoodsSku.getId());
                goodVo.setLimitNumber(sysBizGoodsSku.getLimitNumber());
                goodVo.setLongUnit(sysBizGoodsSku.getLongUnit());
                goodVo.setUnit(sysBizGoodsSku.getUnit());
                goodVo.setUnitNumber(sysBizGoodsSku.getUnitNumber());
                goodVo.setLongUnitNumber(sysBizGoodsSku.getLongUnitNumber());
                goodVo.setMarketPrice(sysBizGoodsSku.getMemberMarketPrice());
                items.add(goodVo);
            }
        }

        Map<Long, Long> goodsMap = items.stream().collect(Collectors.toMap(GoodsEntity::getSkuId, GoodsEntity::getNumber));
        log.error("----------------------- +++++++  ------------------------------ goodsMap skuId <==> Number :{}", goodsMap);
        skuList.forEach(s -> {
            SysBizGoods bizGoods = sysBizGoodsService.getById(s.getGoodsId());

            bizGoods.setSkuId(s.getId());
            bizGoods.setNumber(goodsMap.get(s.getId()));
            // 如果标签不为空就用活动价格
            if (s.getTag() != null) {
                bizGoods.setPrice(s.getActivityPrice());
            } else if (sysBizUser != null) { // 根据身份等级设置商品价格
                if (sysBizUser.getMemberGradeId() == 1) {
                    bizGoods.setPrice(s.getVip1Price());
                }
                if (sysBizUser.getMemberGradeId() == 2) {
                    bizGoods.setPrice(s.getVip2Price());
                }
                if (sysBizUser.getMemberGradeId() == 3) {
                    bizGoods.setPrice(s.getVip3Price());
                }
                if (sysBizUser.getMemberGradeId() == 4) {
                    bizGoods.setPrice(s.getVip4Price());
                }
                if (sysBizUser.getMemberGradeId() == 5) {
                    bizGoods.setPrice(s.getVip5Price());
                }
            }

            list.add(bizGoods);
        });


        List<UserCouponVo> available = new ArrayList<>();
        List<UserCouponVo> notAvailable = new ArrayList<>();
        //总价格
        BigDecimal priceSum = list.stream().map(goods -> goods.getPrice().multiply(new BigDecimal(goods.getNumber()))).reduce(BigDecimal.ZERO, BigDecimal::add);
        for (SysBizCouponReceive sysBizCouponReceive : sysBizCouponReceives) {
            UserCouponVo target = new UserCouponVo();
            BeanUtils.copyProperties(sysBizCouponReceive, target);

            BigDecimal thresholdAmount = target.getThresholdAmount();
            if (target.getTermEndTime().compareTo(new Date()) > 0 && target.getTermBeginTime().compareTo(new Date()) < 0) {

                // 全部商品
                if (1 == sysBizCouponReceive.getScopeUse()) {
                    target.setValidStatus(1);

                    if (priceSum.compareTo(thresholdAmount) >= 0) {
                        target.setValidStatus(0);
                    }
                }
                // 指定商品
                if (2 == sysBizCouponReceive.getScopeUse()) {

                    target.setValidStatus(1);
                    List<Long> goodsIdList = skuList.stream().map(SysBizGoodsSku::getGoodsId).collect(Collectors.toList());
                    List<SysBizCouponGoodsUser> sysBizCouponGoodsUser = sysBizCouponGoodsUserService.getByUserIdAndReceiveIdByGoodsIds2(userId, sysBizCouponReceive.getId(), goodsIdList);
                    if (!CollectionUtils.isEmpty(sysBizCouponGoodsUser)) {
                        //优惠券可用商品的id
                        List<Long> collect = sysBizCouponGoodsUser.stream().map(SysBizCouponGoodsUser::getGoodsId).collect(Collectors.toList());
                        BigDecimal price = new BigDecimal(BigInteger.ZERO);
                        if (!CollectionUtils.isEmpty(collect)) {
                            for (SysBizGoods sysBizGoods : list) {
                                boolean contains = collect.contains(sysBizGoods.getId());
                                if (contains) {
                                    log.error("-------------contains:{} sysBizGoods.getId():{} ,sysBizGoods.getPrice():{}", contains, sysBizGoods.getId(), sysBizGoods.getPrice());
                                    price = price.add(sysBizGoods.getPrice().multiply(new BigDecimal(sysBizGoods.getNumber())));
                                }
                            }
                        }
                        //总价格
                        log.error("-------------thresholdAmount:{},price:{}", thresholdAmount, price);
                        if (price.compareTo(thresholdAmount) >= 0) {
                            target.setValidStatus(0);
                        }
                    }

                }
                // 指定分类
                if (3 == sysBizCouponReceive.getScopeUse()) {
                    target.setValidStatus(1);
                    Map<Long, SysBizCouponMap> longSysBizCouponMapHashMap = new HashMap<>();
                    for (SysBizGoods goods : list) {
                        Long categoryTwoId = goods.getCategoryTwoId();
                        SysBizCouponMap couponMap = longSysBizCouponMapHashMap.get(categoryTwoId);
                        if (couponMap != null) {
                            // 存在，更新
//                            couponMap.getSkuId().add(goods.getSkuId()); // 需要确保getSkuId返回的是可变的列表
                            couponMap.setSumPrice(couponMap.getSumPrice().add(goods.getPrice().multiply(new BigDecimal(goods.getNumber()))));
                            longSysBizCouponMapHashMap.put(categoryTwoId, couponMap);
                        } else {
                            // 不存在，新建
                            couponMap = new SysBizCouponMap();
                            List<Long> skuIdLists = new ArrayList<>();
                            skuIdLists.add(goods.getSkuId());
//                            couponMap.setSkuId(skuIdLists);
                            couponMap.setSumPrice(goods.getPrice().multiply(new BigDecimal(goods.getNumber())));
                            longSysBizCouponMapHashMap.put(categoryTwoId, couponMap);
                        }
                    }
                    log.error("-------------------------id:{}, sysBizCouponReceive.getClassId():{}",sysBizCouponReceive.getId(),sysBizCouponReceive.getClassId());
                    List<Long> classIds = Arrays.stream(sysBizCouponReceive.getClassId().split(","))
                            .map(String::trim)
                            .filter(s -> !s.isEmpty())
                            .map(Long::parseLong)
                            .collect(Collectors.toList());
                    BigDecimal sumPriceCount = new BigDecimal(BigInteger.ZERO);

                    for (Long classId : classIds) {
                        SysBizCouponMap sysBizCouponMap = longSysBizCouponMapHashMap.get(classId);
                        if (sysBizCouponMap != null) {

                            BigDecimal sumPrice = sysBizCouponMap.getSumPrice();
                            sumPriceCount = sumPriceCount.add(sumPrice);
                        }
                    }

                    //总价格
                    if (sumPriceCount.compareTo(thresholdAmount) >= 0) {
                        target.setValidStatus(0);
                    }
                }

                if (target.getValidStatus() == 0) {
                    available.add(target);
                } else {
                    notAvailable.add(target);
                }
            }
        }
        Map<String, List<UserCouponVo>> result = new HashMap<>();
        result.put("available", available);
        result.put("notAvailable", notAvailable);

        return R.ok(result);
    }

    /**
     * 查询商品优惠券（带分页）
     *
     * @param goodsId 商品id
     * @return 优惠券列表
     */
    @GetMapping("/queryCouponByGoodsId")
    public R<PageResult<UserCouponVo>> queryCouponByGoodsId(@RequestParam Long goodsId) {
        startPage();
        SysBizUser loginUser = getLoginUser();


        Long userId = loginUser.getId();
        Long tenantId = loginUser.getTenantId();
        SysBizCouponReceive build = SysBizCouponReceive.builder().status(0).tenantId(tenantId).userId(userId).build();

        List<SysBizCouponReceive> sysBizCouponReceives = sysBizCouponReceiveService.queryCouponByUser(build);


        TableDataInfo dataTable = getDataTable(sysBizCouponReceives);
        List<?> rows = dataTable.getRows();
        ArrayList<UserCouponVo> item = new ArrayList<>();
        for (Object row : rows) {
            SysBizCouponReceive sysBizCouponReceive = (SysBizCouponReceive) row;

            UserCouponVo target = new UserCouponVo();
            BeanUtils.copyProperties(sysBizCouponReceive, target);


            if (target.getTermEndTime().compareTo(new Date()) > 0) {
                target.setValidStatus(0);
                // 指定商品
                if (2 == sysBizCouponReceive.getScopeUse()) {
                    target.setValidStatus(1);
                    SysBizCouponGoodsUser sysBizCouponGoodsUser = sysBizCouponGoodsUserService.getByUserIdAndReceiveId(userId, sysBizCouponReceive.getId(), goodsId);

                    if (sysBizCouponGoodsUser != null) {
                        target.setValidStatus(0);
                    }

                }
                // 指定分类
                if (3 == sysBizCouponReceive.getScopeUse()) {
                    SysBizGoods bizGoods = sysBizGoodsService.getById(goodsId);
                    if (bizGoods != null) {
                        boolean contains = sysBizCouponReceive.getClassId().contains(bizGoods.getCategoryTwoId().toString());
                        if (contains) {
                            target.setValidStatus(0);
                        } else {
                            target.setValidStatus(1);
                        }
                    }
                }

            } else {
                target.setValidStatus(2);
            }
            item.add(target);
        }
        return R.ok(new PageResult<>(dataTable.getTotal(), item));
    }

    /**
     * 查询用户领取优惠券可用商品（带分页）
     *
     * @param id 领取记录id
     * @return 优惠券列表
     */
    @GetMapping("/queryGoodsByCoupon/{id}")
    public R<PageResult<GoodsIndexVo>> queryGoodsByCoupon(@PathVariable Long id) {
        SysBizCouponReceive sysBizCouponReceive = sysBizCouponReceiveService.selectSysBizCouponReceiveById(id);
        List<Long> goodIdList;
        // 全部商品
        if (sysBizCouponReceive.getScopeUse() == 1) {
            LambdaQueryWrapper<SysBizGoods> queryWrapper = new LambdaQueryWrapper<SysBizGoods>().eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey());
            queryWrapper.eq(SysBizGoods::getTenantId, getTenantId());
            goodIdList = sysBizGoodsService.list(queryWrapper.eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()).orderByDesc(SysBizGoods::getOrderNum)).stream().map(SysBizGoods::getId).collect(Collectors.toList());
        } else {
            LambdaQueryWrapper<SysBizCouponGoodsUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysBizCouponGoodsUser::getReceiveId, sysBizCouponReceive.getId());
            queryWrapper.orderByAsc(SysBizCouponGoodsUser::getId);
            List<SysBizCouponGoodsUser> sysBizCouponGoodsList = sysBizCouponGoodsUserService.list(queryWrapper);
            if (CollectionUtils.isEmpty(sysBizCouponGoodsList)) {
                return R.ok(new PageResult<>(0, new ArrayList<>()));
            }
            List<Long> collect = sysBizCouponGoodsList.stream().map(SysBizCouponGoodsUser::getGoodsId).collect(Collectors.toList());
            goodIdList = sysBizGoodsService.list(new LambdaQueryWrapper<SysBizGoods>().eq(SysBizGoods::getGrounding, EnableStatusEnum.ENABLE.getKey()).eq(SysBizGoods::getDeleted, OrderDeleteEnum.NOT_DELETE.getKey()).in(SysBizGoods::getId, collect).orderByDesc(SysBizGoods::getOrderNum)).stream().map(SysBizGoods::getId).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(goodIdList)) {
            return R.ok(new PageResult<>(0, new ArrayList<>()));
        }
        SysBizUser loginUser = sysBizUserService.selectSysBizUserById(getUserId());
        startPage();
        List<GoodsIndexVo> goodsIndexVoList = sysBizUserCollectService.queryCollectByUser(goodIdList, loginUser);
        TableDataInfo dataTable = getDataTable(goodsIndexVoList);
        return R.ok(new PageResult<>(dataTable.getTotal(), goodsIndexVoList));
    }

}
